<template>
  <div style="overflow-y: auto;">
    <div class="header-container">
      <h1>我教的课</h1>
    </div>
    <div class="controls-container">
      <!-- 操作按钮 -->
      <el-row :gutter="10" style="margin-bottom: 15px">
        <el-col :span="1.5">
          <el-button icon="el-icon-plus" plain type="primary">
          </el-button>
        </el-col>
        <el-col :span="1.5" style="margin-left: 68px">
          <refresh-and-hide @refresh="handleRefresh" @toggle-search="handleToggleSearch"/>
        </el-col>
      </el-row>
      <!-- 搜索栏 -->
      <el-form v-show="showSearch" :inline="true" :model="queryParams">
        <el-form-item label="名称:">
          <el-input v-model="queryParams.name" clearable placeholder="请输入课程名"
                    style="width: 150px" @input="handleQuery"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <svg-icon icon-file-name="white-search" style="color: #1abc9c"></svg-icon>
            搜索
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="scroll-container">
      <!-- 表格展示 -->
      <el-table v-loading="loading" :data="teacherCourseList" border @sort-change="handleSortChange" @row-dblclick="handleRowDoubleClick">
        <el-table-column align="center" label="ID" prop="enrollmentId" width="55"></el-table-column>
        <!--缩略图-->
        <el-table-column align="center" label="课程封面" prop="courseImage" width="180">
          <template #default="scope">
            <el-image :lazy="true" :src="scope.row.courseImage" class="image-cover" fit="cover">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <!-- 课程名 -->
        <el-table-column align="center" label="课程名" prop="name" width="160"></el-table-column>
        <!-- 课程描述 -->
        <el-table-column align="center" label="课程描述" prop="description" width="260"></el-table-column>
        <!-- 课程学分 -->
        <el-table-column align="center" label="课程学分" prop="credits" sortable="custom" width="80">
        </el-table-column>
        <el-table-column align="center" label="课程人数" prop="presentNum" sortable="custom" width="80">
        </el-table-column>
        <el-table-column align="center" label="上课时间" prop="upClassTime" sortable width="130">
          <template #default="scope">
            <div class="time">
              <span style="margin-left: 10px">{{formatClassTime(scope.row.week, scope.row.onClass)}}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 创建时间 -->
        <el-table-column align="center" label="创建时间" prop="createTime" sortable width="130">
          <template #default="scope">
            <div class="time">
              <svg-icon icon-file-name="time"></svg-icon>
              <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 更新时间 -->
        <el-table-column align="center" label="更新时间" prop="updateTime" sortable width="130">
          <template #default="scope">
            <div class="time">
              <svg-icon icon-file-name="time"></svg-icon>
              <span style="margin-left: 10px">{{ scope.row.updateTime }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="课堂状态" prop="status">
          <template #default="scope">
            {{ formatStatus(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="选课状态" prop="status">
          <template #default="scope">
            {{ formatSelectStatus(scope.row.selectStatus) }}
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column align="center" label="操作" sortable width="260">
          <template #default="scope">
            <el-button class="sdf" link type="primary" @click="handleCheckStudentInCourse(scope.row.enrollmentId,scope.row.name)">
              <svg-icon icon-file-name="edit"></svg-icon>
              查看学生
            </el-button>
            <el-button class="sdf" link type="primary" @click="handleEdit(scope.row)">
              <svg-icon icon-file-name="edit"></svg-icon>
              编辑
            </el-button>
            <el-button class="sd" link type="primary" @click="handleEnd(scope.row.enrollmentId)">
              <svg-icon icon-file-name="edit"></svg-icon>
              结课
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <pagination v-if="total > 0" :limit="pagInfo.pageSize" :page="pagInfo.currentPage" :total="total"
                style="float: right;" @pagination="getCoursesList"
                @update_limit="pagInfo.pageSize = $event"
                @update_page="pagInfo.currentPage = $event"/>
    <el-dialog :visible.sync="courseStudentListDialogVisible" :title="GetTitle" width="80%">
      <el-button class="sdf" link type="primary" @click="handleAddStudent()">
        <svg-icon icon-file-name="edit"></svg-icon>
        添加学生
      </el-button>
      <el-input v-model="studentNum" clearable placeholder="请输入学生学号"
                style="width: 150px"/>
      <el-input v-model="studentName" clearable placeholder="请输入学生姓名"
                style="width: 150px"/>
      <el-table :data="studentOfTeacherList" style="width: 100%">
        <el-table-column prop="studentId" label="学生ID" width="100"></el-table-column>
        <el-table-column prop="studentNum" label="学号" width="180"></el-table-column>
        <el-table-column prop="name" label="学生姓名"></el-table-column>
        <el-table-column prop="learnCredits" label="已修学分" width="100"></el-table-column>
        <el-table-column prop="grade" label="学生年级" width="100">
          <template #default="scope">
            {{ ['大一', '大二', '大三', '大四'][scope.row.grade - 1] }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="danger" size="small" @click="removeStudent(scope.row.selectInfoId)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog :visible.sync="studentCourseDialogVisible" title="课堂信息" width="50%">
      <el-form :model="selectCourseForm" ref="selectCourseFormRef" :rules="rules">
        <el-form-item :label-width="formLabelWidth" label="课程容量:" prop="maxNum">
          <el-input v-model="selectCourseForm.maxNum" type="number" placeholder="课程容量" style="width: 100px; display: inline-block;"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="上课时间" prop="week">
          <el-select v-model="selectCourseForm.week" placeholder="请选择上课时间">
            <el-option label="星期一" :value="1"></el-option>
            <el-option label="星期二" :value="2"></el-option>
            <el-option label="星期三" :value="3"></el-option>
            <el-option label="星期四" :value="4"></el-option>
            <el-option label="星期五" :value="5"></el-option>
            <el-option label="星期六" :value="6"></el-option>
            <el-option label="星期日" :value="7"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="课程节数(第几节课上课):" prop="onClass">
          <el-select v-model="selectCourseForm.onClass" placeholder="请选择上课时间">
            <el-option label="第一节课" :value="1"></el-option>
            <el-option label="第二节课" :value="2"></el-option>
            <el-option label="第三节课" :value="3"></el-option>
            <el-option label="第四节课" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="此次课程的学生年级:" prop="grade">
          <el-select v-model="selectCourseForm.grade" placeholder="请选择学生年级">
            <el-option label="大一" :value="1"></el-option>
            <el-option label="大二" :value="2"></el-option>
            <el-option label="大三" :value="3"></el-option>
            <el-option label="大四" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="学分限制:">
          <div>
            <el-input v-model="selectCourseForm.minCredits" type="number" placeholder="最低学分" style="width: 100px; display: inline-block;"></el-input>
            <span style="display: inline-block; margin: 0 10px;">至</span>
            <el-input v-model="selectCourseForm.maxCredits" type="number" placeholder="最高学分" style="width: 100px; display: inline-block;"></el-input>
          </div>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="该次课堂结课时间:" prop="endTime">
          <el-date-picker
            v-model="selectCourseForm.endTime"
            type="date"
            placeholder="选择日期"
            format="yyyy/MM/dd"
            value-format="yyyy/MM/dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="该次选课结束时间:" prop="stopTime">
          <el-date-picker
            v-model="selectCourseForm.stopTime"
            type="date"
            placeholder="选择日期"
            format="yyyy/MM/dd"
            value-format="yyyy/MM/dd">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="studentCourseDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="saveSelectCourse">保存</el-button>
  </span>
    </el-dialog>
    <el-dialog :visible.sync="commentListDialogVisible" title="课堂评价" width="50%">
      <el-table v-loading="commentLoading" :data="studentCommentList" border @sort-change="handleSortChange">
        <!-- 表格选择列 -->
        <el-table-column align="center" label="ID" prop="reviewId" width="55"></el-table-column>
        <!-- 评价者 -->
        <el-table-column align="center" label="评价者" prop="studentName" width="120"></el-table-column>
        <!-- 评级内容 -->
        <el-table-column align="center" label="评价内容" prop="content" width="340"></el-table-column>
        <!-- 评价等级 -->
        <el-table-column align="center" label="所评等级" prop="rating" sortable="custom" width="160">
        </el-table-column>
        <!-- 评价时间 -->
        <el-table-column align="center" label="评价时间" prop="createTime" sortable width="150">
          <template #default="scope">
            <div class="time">
              <svg-icon icon-file-name="time"></svg-icon>
              <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import refreshAndHide from "@/common/refreshAndHide.vue";
import Pagination from "@/common/pagination.vue";
import {
  teacherAddStudentToCourse,
  endCourse,
  getCourseStudentList,
  getTeacherCourseList,
  removeStudentFromCourse,
  updateSelectCourse,
  getEnrollmentCommentList
} from "@/apis/teacher";
import axios from "axios";

export default {
  // 组件注册，允许在模板中使用导入的组件
  components: {
    Pagination, // 分页组件
    refreshAndHide // 刷新和隐藏组件
  },
  computed:{
    GetTitle(){
      return this.courseName+'中的学生';
    }
  },
  // 组件的响应数据对象
  data() {
    return {
      courseName: '',
      studentNum: '',
      studentName: '',
      // 控制搜索表单显示的布尔值
      showSearch: true,
      // 搜索参数对象
      queryParams: {
        name: '' // 课程名
      },
      //分页信息
      pagInfo: {
        currentPage: 1,
        pageSize: 10
      },
      // 存储教师课程列表的数组
      teacherCourseList: [],
      // 控制表格加载状态的布尔值
      loading: false,
      commentLoading:false,
      // 存储总课程数量的变量
      total: 0,
      currentEnrollmentId:'',

      courseStudentListDialogVisible: false, // 课程下所有学生信息对话框的显示
      formLabelWidth:'500px',

      // 存储某个课程中的学生信息
      studentOfTeacherList:[],

      rules: {
        maxNum: [
          { required: true, message: '请输入课程容量', trigger: 'change' },
        ],
        week: [
          { required: true, message: '请选择上课时间', trigger: 'change' }
        ],
        onClass: [
          { required: true, message: '请选择上课时间', trigger: 'change' }
        ],
        grade: [
          { required: true, message: '请选择学生年级', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择该次课程结课时间', trigger: 'change' }
        ],
        stopTime: [
          { required: true, message: '请选择该次选课结束时间', trigger: 'change' }
        ]
      },
      isEditing: false, // 控制是否是编辑状态
      studentCourseDialogVisible: false, // 控制编辑对话框的显示
      selectCourseForm: { // 编辑学生课程表单的数据模型
        enrollmentId: '', // 选课信息数据的ID
        teacherId: '',// 给此次选课分配的教师的ID
        maxNum: '', // 此次选课分配的课程的课程容量
        week: '', //此次课程在星期几上课
        onClass: '', // 此次课程在第几节课上课(每天共四节课1-4)
        minCredits: '', // 此次选课的课程的学生的最低学分
        maxCredits: '', // 此次选课的课程的学生的最高学分
        grade: '', // 选课的学生的年级的限制
        endTime: '', // 此次选课的课程的结课时间
        stopTime: '' ,// 此次选课的课程的选课截止时间
      },

      commentListDialogVisible:false,//评价窗可视
      studentCommentList:[],//某课堂的学生评价列表

    };
  },
  methods: {
    formatClassTime(week, onClass) {
      const weekDays = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六','星期日'];
      const classTimes = ['第一节课', '第二节课', '第三节课', '第四节课'];
      return `${weekDays[week - 1]}${classTimes[onClass - 1]}`;
    },
    formatStatus(status) {
      const statusMap = {
        '1': '课程进行中',
        '-1': '已结课'
      };
      return statusMap[status] || '未知状态';
    },
    formatSelectStatus(status) {
      const statusMap = {
        '1': '选课进行中',
        '-1': '选课已结束'
      };
      return statusMap[status] || '未知状态';
    },
    // 老师手动为自己的课堂添加学生
    handleAddStudent(){
      let data = {
        studentNum:this.studentNum,
        enrollmentId:this.currentEnrollmentId,
        studentName: this.studentName
      }
      teacherAddStudentToCourse(data).then(response => {
        if (response.data.code === 1) {
          this.$message.success('添加学生成功');
          // 重新获取课程下的学生列表
          this.handleCheckStudentInCourse(this.currentEnrollmentId,this.courseName);
        } else {
          this.$message.error(response.data.msg);
        }
      });
    },
    removeStudent(selectInfoId) {
      this.$confirm('确定要移除这名学生吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {
          selectInfoId: selectInfoId,
          // 可能还需要其他信息，如课程ID
        };
        removeStudentFromCourse(data).then(response => {
          if (response.data.code === 1) {
            this.$message.success('移除学生成功');
            // 重新获取课程下的学生列表
            this.handleCheckStudentInCourse(this.currentEnrollmentId,this.courseName);
          } else {
            this.$message.error('移除学生失败');
          }
        });
      }).catch(() => {
        // 点击取消或关闭对话框后的处理
      });
    },
    //课程双击事件
    handleRowDoubleClick(row) {
      this.commentListDialogVisible=true;
      //向服务端请求该课程的评价
      this.commentLoading = true;
      let data={
        enrollmentId:row.enrollmentId
      }
       getEnrollmentCommentList(data).then(res => {
        if (res.data.code === 1) {
          this.studentCommentList = res.data.data.list;
          this.commentLoading = false;
        } else {
          this.$message.error(res.data.msg);
        }
      })
      // 在这里添加你的事件处理逻辑
    },
    // 处理查看学生按钮点击事件
    handleCheckStudentInCourse(enrollmentId,courseName) {
      this.courseName=courseName;
      this.formLabelWidth='500px'; // 表单标签宽度
      let data = {
        enrollmentId: enrollmentId
      }
      this.currentEnrollmentId = enrollmentId;
      getCourseStudentList(data).then(res => {
        this.studentOfTeacherList = res.data.data.list;
        this.courseStudentListDialogVisible = true; // 学生信息对话框的显示
      }).catch(error => {
        this.$message.error("获取课程详情失败");
      });
    },
    // 处理编辑选课按钮点击事件
    handleEdit(data) {
      this.formLabelWidth='200px'
      this.isEditing = true;
      this.selectCourseForm = data;
      this.studentCourseDialogVisible = true;
    },
    // 处理结课按钮点击事件
    handleEnd(enrollmentId) {
      let data = {
        enrollmentId: enrollmentId
      }
      endCourse(data).then(res => {
        if (res.data.code === 1) {
          this.$message.success("结课成功");
          this.getCoursesList();
        }
      }).catch(error => {
        this.$message.error("结课失败");
      });
    },
    // 保存课程信息
    saveSelectCourse() {
      this.$refs.selectCourseFormRef.validate((valid) => {
        if (valid) {
          if (this.$common.isEmpty(this.selectCourseForm.minCredits) || this.$common.isEmpty(this.selectCourseForm.maxCredits) || Number(this.selectCourseForm.minCredits) > Number(this.selectCourseForm.maxCredits)){
            this.$message({
              type: 'error',
              message: "学分设置错误"
            });
            return;
          }
          if (this.isEditing) {
            const data = {
              enrollmentId: this.selectCourseForm.enrollmentId,
              maxNum: this.selectCourseForm.maxNum,
              week: this.selectCourseForm.week,
              onClass: this.selectCourseForm.onClass,
              minCredits: this.selectCourseForm.minCredits,
              maxCredits: this.selectCourseForm.maxCredits,
              grade: this.selectCourseForm.grade,
              endTime: new Date(this.selectCourseForm.endTime),
              stopTime:new Date(this.selectCourseForm.stopTime)
            }
            updateSelectCourse(data).then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '编辑成功'
                });
                this.getCoursesList();
                this.studentCourseDialogVisible = false;
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.msg
                });
              }
            })
          }
        } else {
          // 校验未通过
          this.$message.error('表单中有错误，请修正后再提交');
          return false;
        }
      });
    },

    // 前端排序函数
    handleSortChange({prop, order}) {
      if (!order) {
        // 如果没有排序顺序，可能是恢复到未排序状态
        this.getCoursesList();
        return;
      }

      // 根据排序信息对 articleList 进行排序
      // articleList 是一个数组，包含要显示在表格中的文章
      this.teacherCourseList.sort((a, b) => {
        if (order === 'ascending') {
          return a[prop] - b[prop]; // 升序排序
        } else {
          return b[prop] - a[prop]; // 降序排序
        }
      });
    },
    // 处理搜索显示/隐藏的逻辑
    handleToggleSearch() {
      this.showSearch = !this.showSearch;
    },
    // 处理刷新数据的逻辑
    handleRefresh() {
      this.getCoursesList();
      this.$message.success('列表已刷新');
    },
    // 搜索课程的方法
    handleQuery() {
      this.loading = true;
      // 重置当前页为第一页
      this.pagInfo.currentPage = 1;
      const pagination = {
        currentPage: this.pagInfo.currentPage,
        pageSize: this.pagInfo.pageSize
      }
      const queryParams = {
        name: this.queryParams.name,
        teacherName: this.queryParams.teacherName,
      }
      const DTOdata = {
        pagination,
        queryParams//只有搜索时才会带上
      }
      getTeacherCourseList(DTOdata).then(res => {
        if (res.data.code === 1) {
          res.data.data.list.forEach((article) => {
            article.createTime = this.$common.dateFormat(article.createTime);
            article.endTime = this.$common.dateFormat(article.endTime);
            article.updateTime = this.$common.dateFormat(article.updateTime);
          });
          this.teacherCourseList = res.data.data.list;
          this.total = res.data.data.total;
          this.loading = false;
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    // 获取课程列表的方法
    async getCoursesList() {
      this.loading = true;
      const pagination = {
        currentPage: this.pagInfo.currentPage,
        pageSize: this.pagInfo.pageSize
      }
      const queryParams = null;
      const DTOdata = {
        pagination,
        queryParams
      }
      await getTeacherCourseList(DTOdata).then(res => {
        if (res.data.code === 1) {
          res.data.data.list.forEach((course) => {
            course.createTime = this.$common.dateFormat(course.createTime);
            course.updateTime = this.$common.dateFormat(course.updateTime);
            course.endTime = this.$common.dateFormat(course.endTime);
          });
          this.teacherCourseList = res.data.data.list;
          this.total = res.data.data.total;
          this.loading = false;
        } else {
          this.$message.error(res.data.msg);
        }
      })
    }
  },
  created() {
    this.getCoursesList();
  }
};
</script>

<style scoped>
.header-container {
  display: flex;
  justify-content: space-between; /* 使子元素之间的间距最大化，从而将标题推向左边，将搜索栏推向右边 */
  align-items: center; /* 垂直居中对齐子元素 */
  padding: 0 15px; /* 根据需要调整，为容器添加一些内边距 */
  margin-bottom: 20px; /* 根据需要调整，为标题和搜索栏下方留出一些空间 */
}

.controls-container {
  display: flex;
  justify-content: space-between; /* 使子元素分布在容器的两端 */
  align-items: center; /* 垂直居中对齐子元素 */
}


h1 {
  margin: 0; /* 移除默认的外边距 */
  font-size: 30px; /* 根据需要调整标题的字体大小 */
}

.scroll-container {
  max-height: 646px; /* 您可以根据需要调整这个值 */
  overflow-y: auto;
}

.sdf {
  background: transparent;
  border-color: transparent;
  color: #76d7ff;
}

.sd {
  background: transparent;
  border-color: transparent;
  color: #fa1224;
}

.image-cover {
  width: 100px;
  height: 60px;
  border-radius: 5px;
  overflow: hidden;
  cursor: pointer;

  .image-slot {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    color: #909399;
  }
}

.time {
  display: flex;
  align-items: center;
}
</style>



